<template>
  <el-drawer
    title="YRFM配置"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="beforeClose"
    custom-class="tag-drawer yrfm-drawer"
    v-drawerResize
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
          <el-form-item label="分析名称" prop="rfmAnalysisName">
            <el-input v-model="editForm.rfmAnalysisName" placeholder="请输入分析名称"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="description">
            <el-input
              placeholder="请输入备注"
              v-model="editForm.description"
              type="textarea"
              :maxlength="1000"
              :rows="5"
              :show-word-limit="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="字段类型" prop="isTemplateStatus">
            <el-select v-model="editForm.isTemplateStatus" placeholder="请选择字段类型">
              <el-option label="数值型" :value="0"></el-option>
              <el-option label="枚举型" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <template v-if="editForm.isTemplateStatus">
            <el-row>
              <el-col :span="12">
                <el-form-item label="输出配置" prop="tmplType">
                  <el-radio-group v-model="editForm.tmplType">
                    <el-radio-button :label="1">阶层模板</el-radio-button>
                    <el-radio-button :label="2">自定义阶层</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" align="right">
                <el-button type="text" class="tmpl-save" v-if="editForm.tmplType == 2" @click="saveTmpl">
                  <icon-svg name="iconSave"></icon-svg>保存模板
                </el-button>
              </el-col>
            </el-row>
            <el-form-item label="" prop="analysisTemplateId" v-if="editForm.tmplType == 1">
              <div class="tmpl-box">
                <el-row>
                  <el-col :span="12">
                    <el-select v-model="editForm.analysisTemplateId" popper-class="tmpl-select">
                      <el-option label="---" value=""></el-option>
                      <el-option v-for="item in tmplList" :key="item.tmplId" :label="item.tmplNm" :value="item.tmplId">
                        <span>{{ item.tmplNm }}</span>
                        <el-tooltip effect="dark" content="删除模板" placement="top" :enterable="false">
                          <span @click.stop="deleteTmpl(item)" class="tmpl-delete">
                            <i class="el-icon-close"></i>
                          </span>
                        </el-tooltip>
                      </el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
            <el-form-item label="" prop="analysisTemplateParam" v-else>
              <div class="tmpl-box">
                <ul>
                  <li>
                    <el-row :gutter="20">
                      <el-col :span="6" align="center">枚举名</el-col>
                      <el-col :span="10" align="center">备注</el-col>
                      <el-col :span="4" align="center">比例</el-col>
                      <el-col :span="4" align="center"></el-col>
                    </el-row>
                  </li>
                  <li v-for="(item, index) in editForm.analysisTemplateParam" :key="index">
                    <el-row :gutter="20">
                      <el-col :span="6" align="center">
                        <el-form-item
                          :prop="'analysisTemplateParam.' + index + '.enum'"
                          label-width="0"
                          :rules="[
                            { required: true, message: '枚举名不能为空', trigger: 'blur' },
                            { max: 100, message: '枚举名不能超过100个字符', trigger: 'blur' }
                          ]"
                        >
                          <el-input v-model="item.enum"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="10" align="center">
                        <el-form-item
                          :prop="'analysisTemplateParam.' + index + '.description'"
                          label-width="0"
                          :rules="[
                            { required: true, message: '备注不能为空', trigger: 'blur' },
                            { max: 200, message: '枚举名不能超过200个字符', trigger: 'blur' }
                          ]"
                        >
                          <el-input v-model="item.description"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="4" align="center">
                        <el-form-item
                          :prop="'analysisTemplateParam.' + index + '.proportion'"
                          label-width="0"
                          :rules="{ required: true, message: '比例不能为空', trigger: 'blur' }"
                        >
                          <el-input-number v-model="item.proportion" :min="0" :max="100"></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="4" align="left">
                        <el-button
                          type="primary"
                          icon="el-icon-plus"
                          plain
                          circle
                          @click="addRule(index + 1)"
                        ></el-button>
                        <el-button
                          type="primary"
                          icon="el-icon-minus"
                          plain
                          circle
                          v-if="index > 0"
                          @click="removeRule(index)"
                        ></el-button>
                      </el-col>
                    </el-row>
                  </li>
                </ul>
              </div>
            </el-form-item>
          </template>
          <el-form-item label="更新频率" prop="execFrequency">
            <el-radio-group v-model="editForm.execFrequency">
              <el-radio v-for="item in $dictList('$exec_frequency')" :key="item.key" :label="item.key">
                {{ item.value }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="editForm.execFrequency">
            <el-form-item label="执行日期" prop="execDtList" v-if="editForm.execFrequency === 2">
              <el-checkbox-group v-model="editForm.execDtList">
                <el-checkbox v-for="date in 31" :label="date" :key="date">{{ date }}</el-checkbox>
                <el-checkbox :label="999">月末</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="执行星期" prop="execWkList" v-if="editForm.execFrequency === 3">
              <el-checkbox-group v-model="editForm.execWkList">
                <el-checkbox v-for="week in 7" :label="week" :key="week">{{ weekShow(week) }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="执行时间" prop="execTm">
              <el-col :span="12">
                <el-time-picker
                  v-model="editForm.execTm"
                  size="mini"
                  placeholder="执行时间"
                  value-format="HH:mm:ss"
                ></el-time-picker>
              </el-col>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="beforeClose">取消</el-button>
      <el-button type="primary" size="medium" @click="save">确定</el-button>
    </div>
    <tag-tmpl-drawer ref="tagTmplDrawer" :tmplType="4"></tag-tmpl-drawer>
  </el-drawer>
</template>

<script>
export default {
  watch: {
    'editForm.tmplType'(val) {
      if (val == 1) this.getTmplList()
    }
  },
  data() {
    return {
      drawerVisible: false,
      tmplList: [],
      editForm: {
        groupId: '',
        tagId: '',
        rfmAnalysisName: '',
        description: '',
        isTemplateStatus: 0,
        tmplType: 1,
        analysisTemplateId: '',
        analysisTemplateParam: [
          {
            enum: '',
            description: '',
            proportion: ''
          }
        ],
        execFrequency: '',
        execDtList: [],
        execWkList: [],
        execTm: '',
        rfmAnalysisParam: '',
        previewResults: []
      },
      editFormRules: {
        rfmAnalysisName: [
          { required: true, message: '分析名称不能为空', trigger: 'blur' },
          { validator: this.$checkEmpty('分析名称不能为空'), trigger: 'blur' }
        ],
        analysisTemplateId: [{ required: true, message: '模板不能为空', trigger: 'change' }],
        analysisTemplateParam: [{ required: true, message: '特征配置选项不能为空', trigger: 'change' }],
        execFrequency: [{ required: true, message: '更新频率不能为空', trigger: 'change' }],
        execDtList: [{ required: true, type: 'array', min: 1, message: '至少要选择一项', trigger: 'change' }],
        execWkList: [{ required: true, type: 'array', min: 1, message: '至少要选择一项', trigger: 'change' }],
        execTm: [{ required: true, message: '执行时间不能为空', trigger: 'change' }]
      }
    }
  },
  methods: {
    weekShow(week) {
      let str = ''
      switch (week) {
        case 1:
          str = '日'
          break
        case 2:
          str = '一'
          break
        case 3:
          str = '二'
          break
        case 4:
          str = '三'
          break
        case 5:
          str = '四'
          break
        case 6:
          str = '五'
          break
        case 7:
          str = '六'
          break
      }
      return str
    },
    showDrawer(params) {
      this.editForm.groupId = params.groupId || ''
      this.editForm.tagId = params.tagId || ''
      this.editForm.rfmAnalysisName = params.rfmAnalysisName
      this.editForm.description = params.description
      this.editForm.isTemplateStatus = params.isTemplateStatus || 0
      if (this.editForm.isTemplateStatus) {
        if (params.analysisTemplateId) {
          this.editForm.analysisTemplateId = Number(params.analysisTemplateId)
          this.editForm.tmplType = 1
        } else {
          this.editForm.analysisTemplateParam = params.analysisTemplateParam.length
            ? JSON.parse(params.analysisTemplateParam)
            : [
                {
                  enum: '',
                  description: '',
                  proportion: ''
                }
              ]
          this.editForm.tmplType = 2
        }
      }
      this.editForm.execFrequency = params.execFrequency
      this.editForm.execDtList = params.execDtList || []
      this.editForm.execWkList = params.execWkList || []
      this.editForm.execTm = params.execTm || ''
      this.editForm.previewResults = params.previewResults
      this.editForm.rfmAnalysisParam = params.rfmAnalysisParam
      this.getTmplList()
      this.drawerVisible = true
    },
    deleteTmpl(item) {
      this.$confirm(`确定删除模板【${item.tmplNm}】？`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        this.$ajax({
          url: this.$ajax.setUrl(`ast/astTagImageTmpl/${item.tmplId}`),
          method: 'delete',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            if (item.tmplId === this.editForm.analysisTemplateId) this.editForm.analysisTemplateId = ''
            this.getTmplList()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    getTmplList() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagImageTmpl/getAllTemp/4'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tmplList = data.data
        } else {
          // 失败后执行的操作
        }
      })
    },
    saveTmpl() {
      this.$refs.tagTmplDrawer.showDrawer({ json: JSON.stringify(this.editForm.analysisTemplateParam) })
    },
    addRule(index) {
      this.editForm.analysisTemplateParam.splice(index, 0, {
        enum: '',
        description: '',
        proportion: ''
      })
    },
    removeRule(index) {
      this.editForm.analysisTemplateParam.splice(index, 1)
    },
    beforeClose() {
      this.editForm.groupId = ''
      this.editForm.tagId = ''
      this.editForm.rfmAnalysisName = ''
      this.editForm.description = ''
      this.editForm.isTemplateStatus = 0
      this.editForm.analysisTemplateId = ''
      this.editForm.tmplType = 1
      this.editForm.analysisTemplateParam = [
        {
          enum: '',
          description: '',
          proportion: ''
        }
      ]
      this.editForm.execFrequency = ''
      this.editForm.execDtList = []
      this.editForm.execWkList = []
      this.editForm.execTm = ''
      this.editForm.previewResults = ''
      this.editForm.rfmAnalysisParam = ''
      this.drawerVisible = false
    },
    save() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let params = {
            rfmAnalysisName: this.editForm.rfmAnalysisName,
            description: this.editForm.description,
            isTemplateStatus: this.editForm.isTemplateStatus,
            analysisTemplateId: '',
            analysisTemplateParam: '',
            execFrequency: this.editForm.execFrequency,
            execDtList: this.editForm.execDtList || [],
            execWkList: this.editForm.execWkList || [],
            execTm: this.editForm.execTm || '',
            rfmAnalysisParam: this.editForm.rfmAnalysisParam,
            previewResults: this.editForm.previewResults
          }
          if (this.editForm.tmplType === 1) params.analysisTemplateId = this.editForm.analysisTemplateId
          else {
            params.analysisTemplateParam =
              this.editForm.analysisTemplateParam.length && this.editForm.analysisTemplateParam[0].enum
                ? JSON.stringify(this.editForm.analysisTemplateParam)
                : ''
          }
          if (this.editForm.tagId) params.tagId = this.editForm.tagId
          if (this.editForm.groupId) params.groupId = this.editForm.groupId
          this.$ajax({
            url: this.$ajax.setUrl('rfmAnalysis/saveRfmAnalysis'),
            method: 'post',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$emit('callback', {
                tagId: data.data,
                rfmAnalysisName: this.editForm.rfmAnalysisName,
                description: this.editForm.description,
                isTemplateStatus: this.editForm.isTemplateStatus,
                analysisTemplateParam: params.analysisTemplateParam,
                analysisTemplateId: this.editForm.analysisTemplateId,
                execFrequency: this.editForm.execFrequency,
                execDtList: this.editForm.execDtList,
                execWkList: this.editForm.execWkList,
                execTm: this.editForm.execTm
              })
              this.$message.success(data.msg)
              this.beforeClose()
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.yrfm-drawer {
  .el-radio-button {
    margin-right: 5px;
  }
  .el-radio-button__inner {
    border-left: 1px solid #dcdfe6;
    border-radius: 3px 3px 0 0 !important;
  }
  .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    background-color: #4d81ea;
    border-color: #4d81ea;
    box-shadow: -1px 0 0 0 #4d81ea;
  }
  .tmpl-box {
    margin-top: -23px;
    padding: 20px;
    border: 1px solid #ddd;
    border-radius: 0 3px 3px 3px;
    li {
      line-height: 30px;
      padding: 10px 0;
      &:first-of-type {
        font-weight: bold;
        color: #fff;
        background-color: #4d81ea;
        border-radius: 3px;
      }
      .el-input__inner {
        text-align: center;
      }
    }
    min-height: 1px;
    line-height: 40px;
    .el-button.is-circle {
      padding: 5px;
      margin-top: 5px;
      .icon-svg {
        font-size: 16px;
      }
    }
  }
  .tmpl-save {
    color: #4d81ea;
    svg {
      width: 18px;
      height: 18px;
      vertical-align: middle;
      margin: -3px 5px 0 0;
    }
  }
  .el-input-number__decrease,
  .el-input-number__increase {
    display: none;
  }
}
.tmpl-select {
  .tmpl-delete {
    float: right;
    width: 18px;
    height: 18px;
    margin-top: 8px;
    text-align: center;
    line-height: 18px;
    border: 1px solid $theme-color;
    border-radius: 50%;
    opacity: 0.4;
  }
  .el-select-dropdown__item:hover {
    .tmpl-delete {
      opacity: 1;
    }
  }
}
</style>
